package com.lanzuo.yxd.scanner.conveyor;

import cn.hutool.extra.spring.SpringUtil;
import com.ghgande.j2mod.modbus.Modbus;
import com.lanzuo.yxd.scanner.config.LaneConfig;
import com.lanzuo.yxd.scanner.config.ScannerConfig;
import com.lanzuo.yxd.scanner.scanner.ScanResultHolder;
import com.lanzuo.yxd.scanner.scanner.ScannerClient;
import com.lanzuo.yxd.scanner.scanner.ScannerWaitNotifyCoordinator;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author eric
 * <p>
 * 传感器信号检测器
 * <p>
 * 对接yxd的传感器信号量
 */
@Slf4j
public class SensorSignalListener implements Runnable {
    /**
     * TODO 具体情况未知
     */
    static final Integer SIGNAL_EXIST = 1;
    static final Integer SLEEP_SECONDS = 3;

    private final LaneConfig laneConfig;
    private final ScannerWaitNotifyCoordinator coordinator;
    private volatile boolean running = true;

    /**
     * sensor listener init
     *
     * @param laneConfig 轨道配置
     */
    public SensorSignalListener(LaneConfig laneConfig) {
        this.laneConfig = laneConfig;
        this.coordinator = SpringUtil.getBean(ScannerWaitNotifyCoordinator.class);
    }

    public void stop() {
        this.running = false;
    }

    /**
     * 暂停几秒
     */
    private void sleep() {
        try {
            TimeUnit.SECONDS.sleep(SLEEP_SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        try {
            Integer lane = laneConfig.getLaneNo();
            while (running && !Thread.currentThread().isInterrupted()) {
                // 循环检测传感器信号
                ModbusMaster modbusMaster4R = new ModbusMaster(laneConfig.getIp(), Modbus.DEFAULT_PORT);
                Integer signal = modbusMaster4R.readSignal(laneConfig.getSensorAddress());
                if (signal == null) {
                    log.info("传感器信号量为空，程序出现异常");
                    sleep();
                    continue;
                }

                if (SIGNAL_EXIST.equals(signal)) {
                    log.info("捕获到传感器信号, {}, 准备驱动扫码器扫码！", SIGNAL_EXIST);

                    ScannerConfig topScanner = laneConfig.getScanner().stream().filter(v -> "top".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);
                    ScannerConfig bottomScanner = laneConfig.getScanner().stream().filter(v -> "bottom".equalsIgnoreCase(v.getPosition())).findFirst().orElse(null);

                    Boolean topResult = false;
                    // === 扫 top ===
                    if (topScanner != null) {
                        ScanResultHolder topHolder = coordinator.createHolder(lane, topScanner.getIp(), topScanner.getPosition());
                        // 先扫上面的码
                        ScannerClient topClient = new ScannerClient(lane, topScanner.getIp(), topScanner.getPosition());
                        topClient.sendT1();

                        try {
                            // 5秒超时
                            topResult = topHolder.waitForResult(5000);
                            log.info("Lane-{}-Top 扫码校验结果: {}", lane, topResult);
                        } catch (TimeoutException e) {
                            log.warn("Lane-{}-Top 扫码校验超时", lane);
                        }
                    }

                    // === 扫 bottom ===
                    if (!topResult && bottomScanner != null) {
                        ScanResultHolder bottomHolder = coordinator.createHolder(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                        // 先扫上面的码
                        ScannerClient bottomClient = new ScannerClient(lane, bottomScanner.getIp(), bottomScanner.getPosition());
                        bottomClient.sendT1();

                        try {
                            // 5秒超时
                            topResult = topResult || bottomHolder.waitForResult(5000);
                            log.info("Lane-{}-Bottom 扫码校验结果: {}", lane, topResult);
                        } catch (TimeoutException e) {
                            log.warn("Lane-{}-Bottom 扫码校验超时", lane);
                        }
                    }

                    if (topResult) {
                        // 开启进板
                        ModbusMaster modbusMaster4W = new ModbusMaster(laneConfig.getIp(), Modbus.DEFAULT_PORT);
                        // TODO 进板子放行，暂定为1
                        modbusMaster4W.writeSignal(laneConfig.getPanelInAddress(), 1);
                        // TODO  传感器值覆盖，说明已经读值了，测试使用，暂定为0
                        modbusMaster4W.writeSignal(laneConfig.getSensorAddress(), 0);
                    }
                }

                sleep();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("<SensorSignalListener> 传感器检测异常 error: {}", e.getMessage());
        }
    }

}
